package com.android.djlmapp.fragment;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.my.AboutUsActivity;
import com.android.djlmapp.activity.my.DuiZhangActivity;
import com.android.djlmapp.activity.my.FeedBackActivity;
import com.android.djlmapp.activity.my.InOutMoneyActivity;
import com.android.djlmapp.activity.my.JiaKuanActivity;
import com.android.djlmapp.activity.my.MyAccountActivity;
import com.android.djlmapp.activity.my.MySettingActivity;
import com.android.djlmapp.activity.my.ProblemActivity;
import com.android.djlmapp.activity.recharge.AddMoneyActivity;
import com.android.djlmapp.adapter.my.MyBaseRecyclerViewAdapter;
import com.android.djlmapp.adapter.my.MyRecyclerviewAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseFragment;
import com.android.djlmapp.model.my.MyInfo;
import com.android.djlmapp.model.my.MySJInfo;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.util.DensityUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class GeRenZhongXinFragment extends BaseFragment implements View.OnClickListener {
    public static final String TAG = "djlm-my: ";
    List<HashMap<String, Object>> mData;
    Unbinder unbinder;
    @BindView(R.id.ll_my)
    LinearLayout llMy;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.tv_user_hone)
    TextView tvUserHone;
    @BindView(R.id.ll_user_info)
    LinearLayout llUserInfo;
    @BindView(R.id.iv_code)
    ImageView ivCode;
    @BindView(R.id.iv_sys)
    ImageView ivSys;
    @BindView(R.id.my_head_row)
    ImageView myHeadRow;
    @BindView(R.id.iv_user_photo)
    ImageView ivUserPhoto;
    @BindView(R.id.top_bac)
    ImageView topBac;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.my_btn_zhuangzhang)
    Button myBtnZhuangzhang;
    @BindView(R.id.top_notes)
    ImageView topNotes;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.my_account_money)
    TextView myAccountMoney;
    @BindView(R.id.my_account_freeze)
    TextView myAccountFreeze;
    @BindView(R.id.sj_name)
    TextView sjName;
    @BindView(R.id.sj_tel)
    TextView sjTel;
    @BindView(R.id.jl_name)
    TextView jlName;
    @BindView(R.id.jl_tel)
    TextView jlTel;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.title_line)
    View titleLine;
    private int callType = 0;
    private TextView call_num;
    private TextView call_cancle;
    private TextView call_opt;

    private String khjlPhone;
    private String kfPhone;
    private String dlsPhone;

    public static GeRenZhongXinFragment newInstance(String tabName) {
        GeRenZhongXinFragment geRenZhongXinFragment = new GeRenZhongXinFragment();
        geRenZhongXinFragment.tag = tabName;
        return geRenZhongXinFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.fragment_my, container, false);
        unbinder = ButterKnife.bind(this, fragmentView);
        ivCode.setVisibility(View.GONE);
        ivSys.setVisibility(View.GONE);
        myHeadRow.setVisibility(View.VISIBLE);
        topBac.setVisibility(View.GONE);
        homeIvReadpoint.setVisibility(View.GONE);
        topNotes.setVisibility(View.GONE);
        titleLine.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.VISIBLE);
        tvName.setText("我的");
        return fragmentView;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        EventBusUtil.register(this);

        initData();
        initView();

        refresh.setColorSchemeResources(R.color.homeBule);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getUserInfo();
            }
        });
    }


    @Override
    public void initView() {
        Log.i(TAG, "加款/转出" +UserInfoUtils.getUserInfoUtilsInstance().GetBDZCQX());

        RecyclerView recyclerView = (RecyclerView) fragmentView.findViewById(R.id.my_recycler);
        MyRecyclerviewAdapter myRecyclerviewAdapter = new MyRecyclerviewAdapter(mData, _mActivity, R.layout.my_list_item);
        recyclerView.setAdapter(myRecyclerviewAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(_mActivity));
        myRecyclerviewAdapter.setOnItemClickListener(new MyBaseRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //此处进行监听事件的业务处理
                switch (position) {
                    case 0:
                        Log.i(TAG, "常见问题");
                        startActivity(new Intent(_mActivity, ProblemActivity.class));
                        break;
                    case 1:
                        Log.i(TAG, "关于我们");
                        startActivity(new Intent(_mActivity, AboutUsActivity.class));

                        break;
                    case 2:
                        Log.i(TAG, "意见反馈");
                        startActivity(new Intent(_mActivity, FeedBackActivity.class));
                        break;
                    case 3:
                        Log.i(TAG, "平台客服电话");
                        callType = 3;
                        showPhoneListDialog(callType);
                        break;
                }
            }
        });

    }

    @Override
    public void initData() {

        mData = new ArrayList<>();
        HashMap<String, Object> hashMap = new HashMap();
        hashMap.put("name", "常见问题");
        hashMap.put("ico", R.mipmap.my_question);
        mData.add(hashMap);
        hashMap = new HashMap();
        hashMap.put("name", "关于我们");
        hashMap.put("ico", R.mipmap.my_ours);
        mData.add(hashMap);
        hashMap = new HashMap();
        hashMap.put("name", "意见反馈");
        hashMap.put("ico", R.mipmap.my_reback);
        mData.add(hashMap);
        hashMap = new HashMap();
        hashMap.put("name", "平台客服电话");
        hashMap.put("ico", R.mipmap.my_service);
        mData.add(hashMap);

        getUserInfo();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBusUtil.unregister(_mActivity);
    }

    @Override
    protected void receiveEvent(Event event) {
        if (event.getCode() == EventCodes.EventMyCode.A) {

            // 加载圆形头像
            RequestOptions options = new RequestOptions().bitmapTransform(new CircleCrop())
                    .placeholder(R.mipmap.home_nomphoto) //图片加载出来前，显示的图片
                    .fallback(R.mipmap.home_nomphoto)  //url为空的时候,显示的图片
                    .error(R.mipmap.home_nomphoto); //图片加载失败后，显示的图片

            // 加载头像
            Glide.with(_mActivity)
                    .load(event.getData().toString())
                    .apply(options)
                    .into(ivUserPhoto);

            UserInfoUtils utils = UserInfoUtils.getUserInfoUtilsInstance();
            utils.setHeadImg(event.getData().toString());

        } else if (event.getCode() == EventCodes.EventMyCode.B) {
            String mobile = event.getData().toString();
            if (!TextUtils.isEmpty(mobile)) {
                mobile = mobile.replace(mobile.substring(3, 7), "****");
                tvUserHone.setText(mobile);
            }
        }
    }

    private void getUserInfo() {
        MyApplication.getInstance().getHttpTools().getMyData(mHOmeStringCallback);
    }


    private StringCallback mHOmeStringCallback = new StringCallback() {

        @Override
        public void onSuccess(Response<String> response) {
            Log.i(TAG, response.body());

            try {
                String body = response.body();
                Log.i(TAG, body);

                Gson gson = new Gson();
                MyInfo info = gson.fromJson(body, MyInfo.class);
                if (info != null) {
                    int code = info.getCode();
                    if (code < 1000) {
                        setMessage(info);
                    } else {
                        tvAccount.setText("---"); //设置账号
                        tvUserHone.setText("---"); // 设置电话
                        myAccountMoney.setText("---");
                        myAccountFreeze.setText("---");

                        ToastUtils.showLongToast(_mActivity, info.getMsg());
                    }
                } else {
                    ToastUtils.showLongToast(_mActivity, "未获取到数据");
                }
            } catch (Exception e) {
                Log.e(TAG, "个人信息数据解析异常" + e.toString());
                ToastUtils.showShortToast(_mActivity, "个人数据解析异常");
            }
        }

        @Override
        public void onError(Response<String> response) {
            super.onError(response);
            String body = response.body();
            Log.e(TAG, "-----onError------" + body);
            ToastUtils.showShortToast(_mActivity, "网络或服务器错误");
        }

        @Override
        public void onFinish() {
            super.onFinish();
            refresh.setRefreshing(false);
            if ("1".equals(UserInfoUtils.getUserInfoUtilsInstance().GetBDZCQX())) {
                myBtnZhuangzhang.setText("加款/转出");
            } else {
                myBtnZhuangzhang.setText("加款");
            }
        }
    };

    private void setMessage(MyInfo info) {
        MyInfo.DataBean dataBean = info.getData();
        String userName = dataBean.getUser_name();
        String mobile = dataBean.getMobile();

        MyInfo.KfDataBean kf = info.getKf_data();
        if (kf != null) {
            sjName.setText(kf.getUser_name());
            sjTel.setText(kf.getMobile());
            jlName.setText(kf.getAccount_user_name());
            jlTel.setText(kf.getAccount_tel());

            // 客服电话
            kfPhone = kf.getKf_mobile();
            // 客户经理电话
            khjlPhone = kf.getAccount_tel();
            // 代理商电话
            dlsPhone = kf.getMobile();
        } else {
            //请求上级代理商信息接口
            getSjInfo();
        }

        //获取个人数据,保存本地
        UserInfoUtils utils = UserInfoUtils.getUserInfoUtilsInstance();
        utils.setMobile(mobile);
        utils.setRelName(dataBean.getC_name()); //真实姓名
        utils.setHeadImg(dataBean.getImg());  //头像
        utils.setBDZCQX(dataBean.getIs_zhuanzhang());  //转出权限

        Log.i(TAG, "--GetBDZCQX" +dataBean.getIs_zhuanzhang());
        Log.i(TAG, "GetBDZCQX" +UserInfoUtils.getUserInfoUtilsInstance().GetBDZCQX());

        MyInfo.UserMoneyBean.EleWalletBean wallet = info.getUser_money().getEle_wallet();
        if (wallet != null) {
            utils.setBD_ZFB(wallet.getAlipay()); //绑定支付宝
            utils.setBD_YHK(wallet.getBank_card()); //绑定银行卡
            utils.setBDSMRZ(wallet.getAuthentication());//实名认证
            utils.setZFBRATE(wallet.getAlipay_rate());//支付宝手续费费率
            utils.setYHKRATE(wallet.getBank_rate());//银行卡手续费费率
            utils.setBankLogo(wallet.getBank_logo());//银行卡logoURL
            utils.setBDBCID(wallet.getBank_card_id());//银行卡id
        }
        utils.setYU_E(info.getUser_money().getMoney());

        tvAccount.setText(userName); //设置账号
        mobile = mobile.replace(mobile.substring(3, 7), "****");
        tvUserHone.setText(mobile); // 设置电话
        myAccountMoney.setText(info.getUser_money().getMoney());
        myAccountFreeze.setText(info.getUser_money().getFreeze_money());

        if(dataBean.getImg() != null){
            // 加载头像
            RequestOptions options = new RequestOptions().bitmapTransform(new CircleCrop())
                    .placeholder(R.mipmap.home_nomphoto) //图片加载出来前，显示的图片
                    .fallback(R.mipmap.home_nomphoto)  //url为空的时候,显示的图片
                    .error(R.mipmap.home_nomphoto); //图片加载失败后，显示的图片

            // 加载头像
            Glide.with(_mActivity)
                    .load(dataBean.getImg())
                    .apply(options)
                    .into(ivUserPhoto);
        }

    }

    AlertDialog dialog;

    private void showPhoneListDialog(int callType) {
        // 创建弹窗对象
        dialog = new AlertDialog.Builder(_mActivity).create();
        dialog.setCancelable(false);

        // 自定义弹窗布局
        View convertView = View.inflate(_mActivity, R.layout.phone_dialog,null);

        call_num = (TextView) convertView.findViewById(R.id.call_num);
        call_cancle = (TextView) convertView.findViewById(R.id.call_cancle);
        call_opt = (TextView) convertView.findViewById(R.id.call_opt);

        boolean isCall = false;
        switch (callType) {
            case 1:
                call_num.setText(khjlPhone);
                if(khjlPhone != null && !khjlPhone.isEmpty()){
                    isCall = true;
                }
                break;
            case 2:
                call_num.setText(dlsPhone);
                if(dlsPhone != null && !dlsPhone.isEmpty()){
                    isCall = true;
                }
                break;
            case 3:
                call_num.setText(kfPhone);
                if(kfPhone != null && !kfPhone.isEmpty()){
                    isCall = true;
                }
                break;
        }

        if (isCall) {
            dialog.show();

            Window window = dialog.getWindow();
            if (window != null) {
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            }
            window.setLayout(DensityUtil.dp2px(280), LinearLayout.LayoutParams.WRAP_CONTENT);

            call_cancle.setOnClickListener(this);
            call_opt.setOnClickListener(this);

            call_cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

            window.setContentView(convertView);
        }
    }

    @OnClick({R.id.ll_my, R.id.my_btn_zhuangzhang, R.id.iv_top_set, R.id.ll_account, R.id.ll_ydetail, R.id.sj_click, R.id.kh_click})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_my:
                startActivity(new Intent(_mActivity, MyAccountActivity.class));
                break;
            case R.id.my_btn_zhuangzhang: //加款转出
                if ("1".equals(UserInfoUtils.getUserInfoUtilsInstance().GetBDZCQX())) {
                    startActivity(new Intent(_mActivity, InOutMoneyActivity.class));
                } else {
                    startActivity(new Intent(_mActivity, AddMoneyActivity.class));
                }
                break;
            case R.id.iv_top_set:
                startActivity(new Intent(_mActivity, MySettingActivity.class));
//                startActivity(new Intent(_mActivity, LivenessActivity.class));
                break;
            case R.id.ll_account: //对账明细
                startActivity(new Intent(_mActivity, DuiZhangActivity.class));
                break;
            case R.id.ll_ydetail://加款记录
                startActivity(new Intent(_mActivity, JiaKuanActivity.class));
                break;
            case R.id.kh_click:
                callType = 1;
//                GeRenZhongXinFragmentPermissionsDispatcher.needPermissionWithCheck(this);
                showPhoneListDialog(callType);
                break;
            case R.id.sj_click:
                callType = 2;
//                GeRenZhongXinFragmentPermissionsDispatcher.needPermissionWithCheck(this);
                showPhoneListDialog(callType);
                break;
            case R.id.call_opt:
                GeRenZhongXinFragmentPermissionsDispatcher.needPermissionWithCheck(this);
                break;
        }
    }

    @NeedsPermission(Manifest.permission.CALL_PHONE)
    void needPermission() {
        String call = "";
        switch (callType) {
            case 1:
                call = khjlPhone;
                break;
            case 2:
                call = dlsPhone;
                break;
            case 3:
                call = kfPhone;
                break;
        }

        Log.i(TAG, "call: " + call);

        if (dialog != null && !TextUtils.isEmpty(call)) {
            dialog.dismiss();

            // 跳转打电话界面
            Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + call));//直接拨打电话
            startActivity(dialIntent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        GeRenZhongXinFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.CALL_PHONE)
    void showRationale(final PermissionRequest request) {
        new AlertDialog.Builder(_mActivity)
                .setMessage("此功能需要电话权限,请允许")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();//继续执行请求
                    }
                }).setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                request.cancel();//取消执行请求
            }
        }).show();
    }

    @OnPermissionDenied(Manifest.permission.CALL_PHONE)
    void multiDenied() {
        ToastUtils.showShortToast(_mActivity, "权限不足,您没有开启此应用的电话权限。请到系统设置-->权限管理 开启电话权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下电话权限！");

    }

    @OnNeverAskAgain(Manifest.permission.CALL_PHONE)
    void multiNeverAsk() {
        ToastUtils.showShortToast(_mActivity, "权限不足,您没有开启此应用的电话权限。请到系统设置-->权限管理 开启电话权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下电话权限！");
    }

    private void getSjInfo() {
        MyApplication.getInstance().getHttpTools().getSJ(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    Log.i(TAG, response.body());
                    Gson gson = new Gson();
                    MySJInfo sjInfo = gson.fromJson(response.body(), MySJInfo.class);

                    if (sjInfo != null) {
                        if (sjInfo.getCode() < 1000) {

                            sjName.setText(sjInfo.getData().getUser_name());
                            sjTel.setText(sjInfo.getData().getMobile());
                            jlName.setText(sjInfo.getData().getAccount_user_name());
                            jlTel.setText(sjInfo.getData().getAccount_tel());

                            // 客服电话
                            kfPhone = sjInfo.getData().getKf_mobile();
                            // 客户经理电话
                            khjlPhone = sjInfo.getData().getAccount_tel();
                            // 代理商电话
                            dlsPhone = sjInfo.getData().getMobile();
                        } else {
                            ToastUtils.showShortToast(_mActivity, sjInfo.getMsg());
                        }
                    } else {
                        ToastUtils.showShortToast(_mActivity, "未获取到数据");
                    }
                } catch (Exception e) {
                    ToastUtils.showShortToast(_mActivity, "数据解析异常");
                }

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                Log.e(TAG, "-----onError------" + response.body());
                ToastUtils.showShortToast(_mActivity, "网络或服务器错误");
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }
}